[LegacyColorValue = true]; 

{ TSM Moving Average Volatility Exits 
  Copyright 2011 P J Kaufman. All rights reserved. }

{  period = length of calculaton
	volperiod = length of volatility calculation
   highvolfilter	 <> 0 then don't enter if volatiltiy > hvf*stdev of returns
   lowvolfilter     <> 0 don't enter if volatility < lvf*stdev of returns
}
   input: period(40), volperiod(20), exitabove(5);
   vars:	signal(0), printPL(true), size(1), investment(25000), equity(0),
  			allocation(0.05), returns(0), vol(0), hvexit(0), exitvol(0);
  			
  	If Currentbar = 1 then equity = investment;

{	atrange = avgtruerange(ATRper);
	if atrange = 0 then 
			size = 1
		else
			size = equity*allocation/atrange; }
	returns = close/close[1] - 1;
	vol = stddev(returns,volperiod);
  	signal = TSM_MAsignal(period,0);
  	if signal <> signal[1] then hvexit = 0;
  	
{ high-volatility exit }
	if vol > exitabove*absvalue(returns) and marketposition*returns > 0 then begin
		if marketposition > 0 then begin
				sell ("Svol") this bar on close;
				hvexit = 1;
				exitvol = absvalue(returns);
				end
			else if marketposition < 0 then begin
				buy to cover ("Bvol") this bar on close;
				hvexit = -1;
				exitvol = absvalue(returns);
			end;
		end;
		
{ reenter after volatility declines }
	if hvexit <> 0 and absvalue(returns) < exitvol/4 then begin
		if hvexit > 0 then buy ("Breset") size contracts this bar on close
			else if hvexit < 0 then sell short ("Sreset") size contracts this bar on close;
		hvexit = 0;
		end;		
		
{ new positions }  	
  	if signal > 0 and hvexit <> 1 and marketposition < 1 then begin
  			if marketposition < 0 then buy to cover ("XStrend") this bar at close;
  			Buy ("Btrend") size contracts This Bar at close;
   		end
  		else if signal < 0 and hvexit <> -1 and marketposition > -1 then begin
  			if marketposition > 0 then sell ("XLtrend") this bar at close;
   		Sell short ("Strend") size contracts This Bar at close;
  		end;
  			
  	equity = equity + marketposition*size[1]*(Close - close[1])*bigpointvalue;
  	
  	If printPL then begin
  		If Currentbar = 1 then print(file("c:\TSM5\MA_volatility_exits.csv"),
  				"Date,signal,position,size,netPL,Equity,returns,vlty");
  		print(file("c:\TSM5\MA_filtered_PL.csv"),date:8:0, ",", signal:5:0, ",", 
  						marketposition:5:0, ",", size:8:3, ",", 
  						netprofit + openpositionprofit:5:5, ",", equity:8:4, ",", returns:4:4,
  						",", vol:4:4);
		end;